package com.oa.erp.ass.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.erp.ass.entity.AssetCard;
import com.oa.erp.ass.entity.AssetDetail;
import com.oa.erp.ass.service.AssetCardService;
import com.oa.erp.ass.service.AssetDetailService;
import com.oa.erp.pur.entity.StockIn;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@RestController
@RequestMapping(value = "/*/oa/erp/ass/assetDetail")
@Api(tags = {"ass_asset_detail-操作接口"})
public class AssetDetailController {

    static Logger logger = LoggerFactory.getLogger(AssetDetailController.class);

    @Autowired
    private AssetDetailService assetDetailService;

    @Autowired
    private AssetCardService assetCardService;

    @ApiOperation(value = "ass_asset_detail-查询列表", notes = " ")
    @ApiEntityParams(AssetDetail.class)
    @ApiResponses({@ApiResponse(code = 200, response = AssetDetail.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listAssetDetail(@ApiIgnore @RequestParam Map<String, Object> params) {
        RequestUtils.transformArray(params, "categoryIds");
        RequestUtils.transformArray(params, "cbCenterIds");
        RequestUtils.transformArray(params, "useDeptids");

        User user = LoginUtils.getCurrentUserInfo();
        params.put("branchId", user.getBranchId());
        QueryWrapper<AssetDetail> qw = QueryTools.initQueryWrapper(AssetDetail.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = assetDetailService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }


    @ApiOperation(value = "ass_asset_detail-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = AssetDetail.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addAssetDetail(@RequestBody AssetDetail assetDetail) {
        boolean createPk = false;
        if (!StringUtils.hasText(assetDetail.getId())) {
            createPk = true;
            assetDetail.setId(assetDetailService.createKey("id"));
        }
        if (createPk == false) {
            if (assetDetailService.selectOneObject(assetDetail) != null) {
                return Result.error("pk-exists", "编号重复，请修改编号再提交");
            }
        }
        if (!StringUtils.hasText(assetDetail.getAssetSn())) {
            return Result.error("assetSn-not-exists", "资产编码不能为空，请修改资产编码再提交");
        }
        assetDetailService.insert(assetDetail);
        return Result.ok("add-ok", "添加成功！").setData(assetDetail);
    }

    @ApiOperation(value = "创建资产编码", notes = "查询资产编码是否重复")
    @ApiResponses({@ApiResponse(code = 200, response = StockIn.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/createAssetSn", method = RequestMethod.POST)
    public Result createAssetSn(@RequestBody AssetDetail assetDetail) {
        User user = LoginUtils.getCurrentUserInfo();
        if (!StringUtils.hasText(assetDetail.getCategoryId())) {
            return Result.error("categoryId-0", "资产分类不能为空");
        }
        String assetSn = this.assetDetailService.createAssetSn(assetDetail.getCategoryId(), user.getBranchId());
        return Result.ok("", "创建资产编码成功").setData(assetSn);
    }

    @ApiOperation(value = "ass_asset_detail-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delAssetDetail(@RequestBody AssetDetail assetDetail) {
        if (!StringUtils.hasText(assetDetail.getId())) {
            return Result.error("pk-not-exists", "请上送主键参数id");
        }
        AssetDetail assetDetailDb = assetDetailService.selectOneById(assetDetail);
        if (assetDetailDb == null) {
            return Result.error("data-not-exists", "数据不存在，无法删除");
        }
        if (!"0".equals(assetDetailDb.getAssetStatus()) && !"4".equals(assetDetailDb.getAssetStatus())) {
            return Result.error("status-not-0|4", "当前资产不是闲置、报废状态，无法删除");
        }
        AssetCard card = new AssetCard();
        card.setDetailId(assetDetailDb.getId());
        long cardNum = assetCardService.countByWhere(card);
        if (cardNum > 0) {
            return Result.error("card-exists", "当前资产下有" + cardNum + "个卡片信息，请先清除卡片信息");
        }
        assetDetailService.deleteByPk(assetDetail);


        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "ass_asset_detail-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = AssetDetail.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editAssetDetail(@RequestBody AssetDetail assetDetail) {
        if (!StringUtils.hasText(assetDetail.getId())) {
            return Result.error("pk-not-exists", "请上送主键参数id");
        }
        AssetDetail assetDetailDb = assetDetailService.selectOneObject(assetDetail);
        if (assetDetailDb == null) {
            return Result.error("data-not-exists", "数据不存在，无法修改");
        }
        assetDetailService.updateSomeFieldByPk(assetDetail);
        return Result.ok("edit-ok", "修改成功！").setData(assetDetail);
    }

    @ApiOperation(value = "ass_asset_detail-批量修改某些字段", notes = "")
    @ApiEntityParams(value = AssetDetail.class, props = {}, remark = "ass_asset_detail", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = AssetDetail.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        assetDetailService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "ass_asset_detail-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelAssetDetail(@RequestBody List<AssetDetail> assetDetails) {
        User user = LoginUtils.getCurrentUserInfo();
        if (assetDetails.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<AssetDetail> datasDb = assetDetailService.listByIds(assetDetails.stream().map(i -> i.getId()).collect(Collectors.toList()));
        List<AssetDetail> can = new ArrayList<>();
        List<AssetDetail> no = new ArrayList<>();
        for (AssetDetail data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            assetDetailService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }
        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "ass_asset_detail-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = AssetDetail.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(AssetDetail assetDetail) {
        AssetDetail data = (AssetDetail) assetDetailService.getById(assetDetail);
        return Result.ok().setData(data);
    }

}
